package test2;

public class Common {
	static Object obj = new Object();
	static Object proObj = new Object();
	static Object conObj = new Object();
	static Buf buf = new Buf();

	public static void main(String[] args) {
		Cons con1 = new Cons();
		Cons con2 = new Cons();
		Cons con3 = new Cons();
		Pro pro1 = new Pro();
		Pro pro2 =new Pro();
		con1.start();
		con2.start();
		con3.start();
		pro1.start();
		pro2.start();
	}

}

class Pro extends Thread {
	public  void run() {
		int i = 0;
		while (i++ < 100) {
			synchronized (Common.obj) {
				if (Common.buf.isFull()) {
					try {
						synchronized (Common.proObj) {
							Common.proObj.wait();
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				Common.buf.put();
				synchronized (Common.conObj) {
					Common.conObj.notify();
				}
				try {
					sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

class Cons extends Thread {
	public void run() {
		int i = 0;
		while (true) {
			synchronized (Common.obj) {
				if (Common.buf.isEmpty()) {
					try {
						synchronized (Common.conObj) {
							Common.conObj.wait();
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				Common.buf.get();
				synchronized (Common.proObj) {
					Common.proObj.notify();
				}
				try {
					sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}

}

class Buf {
	final int MAX = 10;
	int[] buf = new int[MAX];
	int current = 0;
	int i;

	synchronized boolean isFull() {
		if (current >= MAX)
			return true;
		return false;
	}

	synchronized boolean isEmpty() {
		if (current <= 0)
			return true;
		return false;
	}

	synchronized void put() {
		buf[current++] = i++;
		System.out.println("              " + Thread.currentThread().getName()
				+ ":" + i);
	}

	synchronized void get() {
		System.out.println(Thread.currentThread().getName() + ":" + buf[--current]);
	}

}